import Vue from 'vue'
import Vuex from '@/store/index.js'
import axios from 'axios'
import isIEBrowser from '@/utils/isIe'
import {  getCookie,clearAllCookie } from '@/utils/cookie.js'

const service = axios.create({
    baseURL:
        process.env.NODE_ENV === 'devServe'
            ? '/apiDev'
            : process.env.VUE_APP_BASEURL,
    timeout: 6000000000, // 请求超时时间
})


const err = (error) => {
    changeRequest()
    if (error.response) {
        let { data, message } = error.response
        Vue.prototype['$message'].error(data || message)
    } else {
        Vue.prototype['$message'].error(error)
    }

    return Promise.reject(error)
}

let timer = null;


  
let changeRequest = ()=>{
    if(timer)clearTimeout(timer)
    timer =  setTimeout(()=>{
        Vuex.commit('user/muLoadingStatus',false)
    },500)
}

service.interceptors.request.use(
    (config) => {
        if(Vuex.state.user.topLoadingStatus == false){
            Vuex.commit('user/muLoadingStatus',true)
        }
        if (config.method === 'get') {
            config.data = { unused: 0 }
        }

        // console.log(sessionStorage.getItem('tokenIframe'))
        // console.log(getCookie('pathToken'))

        let token =
            (process.env.NODE_ENV === 'devServe')
                ?
                sessionStorage.getItem('tokenIframe') 
             
             || "aGNieDhzd202V0xHaW1raHNMbktGK2xFQzJqeWRpT0h0QlZQaVdYRXRpQ2lTc1hLZ1ZWVzA1UllzL0FFSVN0RnQ4WENFRlU0OEdaLwp6MlJBSmlwRzFRN21rdU4vejJoSmdiRUt0MUJDNVlLU05tNFo0djdneVIrL1R0Vk05Nm5XSmx0dXJzSVNOU3FvZk9sZVV0c2pSb1JmCmg1eWkxVUkzY3BERzJFSmQwTWJLVmh5QndveENMeHIyazgxQzUzTlFPYjVlQU9lUit5MTladWhQL1JHQ1Nkd2p0VVZNeUtkcXl1VUcKbVFHeTJpWFZGQlBsMnlxRUJScVlwMVZ1S0swYk1mcHp6TXdxZmhkQTgyWGh3cStQbUE9PQ_"
            //  ||  'SjNlTEtNMlJFbGVvUElDQ1Z2MlJoN1NZNzQ1MmVpS04wR2dQTnF5MjFnblZ0RXVrMDlheWt6bE45U1JHaEs1bm1md3J1N3daWDNIVgo4eUUycnJXRWpzOU13RkhDMHU5THhaNnEzbTY1SjdVd1lzR1pHS0F4Z0JCdXczTHhSWk9xRDZ2UXpVK0NZSmF1WXp6TVdveXV0dWtICmMyTUpzaUJER09ueiswV2VJTFBPRElUZWNvRUh0aWoydUZRa2xCanp2U2tDYWdicFc0Vlp1NktDMjlEMnQyRFhhd3hpVG1qMEFpaW0Ka3RZVlcweTN2NmZGVnF5UDdXaG5ISlNLSC9LM2hTT1k0UkhENWg4YVg5a2t2V05sQThTZm5mbWJPNTg4RmtUaTcrZ0xsYTl6ZDJkQQpDRkpjVWhyMms4MUM1M05RdzVHTmNKZ0R1bVZXYXFwdWdNbWFLQT09'  

             
                :  sessionStorage.getItem('tokenIframe') || getCookie('pathToken') ;
// 这里把会话放前面

        config.headers['Authorization'] = token
        if (config.method == 'get') {
            if (config.params) {
                config.params['newDate' + new Date().getTime()] =
                    new Date().getTime()
            } else {
            }
        } 

        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)


  // 是否正在刷新的标记
let isRefreshing = false
// 重试队列，每一项将是一个待执行的函数形式
let requests = []
function refreshTokenFetch () {
    // instance是当前request.js中已创建的axios实例
    return service.post('/vatoutinv/login/refreshToken?reToken=' + sessionStorage.getItem('refreshTokenCache')).then(res => res.data)
}

  
service.interceptors.response.use((response) => {
    changeRequest()
    if (response.config.responseType == 'blob') {
        if(response.data.type == "application/json"){
            if(isIEBrowser()){
                try {
                    const blob = new Blob([response.data]);
                    const reader = new FileReader();
                    reader.onload = function (e) {
                      const text = e.target.result;
                      try {
                        const jsonData = JSON.parse(text);
                        Vue.prototype['$message'].error("解析返回数据异常,异常信息:" + jsonData.message);
                      } catch (error) {
                        Vue.prototype['$message'].error("解析返回数据异常");
                      }
                    };
                    reader.readAsText(blob);
                  } catch (error) {
                    Vue.prototype['$message'].error("解析返回数据异常");
                  }
            }else{
                try{
                    response.data.text().then(data=>{
                        const jsonData =    JSON.parse(data);
                        Vue.prototype['$message'].error("解析返回数据异常,异常信息:" + jsonData.message)
                    })
                }catch(e){
                    Vue.prototype['$message'].error("解析返回数据异常")
                }

            }

        }
        return response
    }
    let { code, data, message } = response.data
    if (code != 200) {
        if (code === '7012') {
            // excel数据校验不通过,手工发票开具不通过
            return response.data
        } else if (code === '7300') {
            // excel数据校验不通过,手工发票开具不通过
            return response.data
        } else if (code === '7200') {
            // 开票
            Vue.prototype.$errorRef.open({
                isShow: true,
                contentArray: data,
            })
        } else if(code === '2000'){
            Vue.prototype['$message']({
                message: message || data,
                type: 'success',
                duration: 5000,
            })
            return {
                ...response.data,
                code : 200
            }
        } else if (code === '300') {
            Vue.prototype['$message']({
                message: message,
                type: 'error',
                duration: 5000,
            })
        }else if(code === '9996') {
            const config = response.config
            if (!isRefreshing) {
                isRefreshing = true
                return refreshTokenFetch().then(res => {
                    const { token,refreshToken } = res
                    // setCookie('pathToken', '') // 刷新应该不需要重置cookie的
                    // clearAllCookie()
                    sessionStorage.setItem('tokenIframe', token)
                    sessionStorage.setItem('refreshTokenCache', refreshToken)
                    config.headers['Authorization'] = token
                    requests.forEach(cb => cb(token))
                    requests = []
                    return service(config)
                }).catch(res => {
                    sessionStorage.setItem('tokenIframe', '')
                    sessionStorage.setItem('refreshTokenCache', '')
                    Vue.prototype['$confirm']( `登录信息已过期，请重新登录增值税管理系统`,'提示').then(data=>{
                        try {
                            sessionStorage.setItem('tokenIframe', '')
                            sessionStorage.setItem('refreshTokenCache', '')
                            // 跳转到新页面或资源
                            window.location.replace(process.env.VUE_APP_JUMPURL);

                            Vuex.commit("user/muRouteTreeToList",[]);
                            Vuex.commit("user/muRouteListHandler",[]);
                            Vuex.commit("user/muBtnList",[]);
                            Vuex.commit("user/muGetedRouteList",false);

                        } catch (error) {
                          
                        }
                    },err=>{
                      try {
                        

                            sessionStorage.setItem('tokenIframe', '')
                            sessionStorage.setItem('refreshTokenCache', '')
                            window.location.replace(process.env.VUE_APP_JUMPURL);
                        } catch (error) {
                          
                        }
                    })

                }).finally(() => {
                    isRefreshing = false
                })
            } else {
                return new Promise((resolve) => {
                    requests.push((token) => {
                        config.headers['Authorization'] = token
                        resolve(service(config))
                    })
                })
            }
        }else if(code == 9997){
            return  window.location.replace(process.env.VUE_APP_JUMPURL);
         }
        else {
            Vue.prototype['$message']({
                message: message || data,
                type: 'error',
                duration: 5000,
            })
        }

    }else  if(code == 200){
        if(response.config.url == '/vatoutinv/login/refreshToken'){

        }
    }
    return response.data
}, err)

export {
    service as axios,
}
